package tv_megazineplus

import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.DefaultValue
import javax.ws.rs.core.Response
import groovy.sql.Sql
import com.google.gson.Gson
import org.codehaus.groovy.runtime.TimeCategory


@Path('/api/getUserStatsXML')
class GetUserStatsXMLResource {

    @GET
    @Produces('text/xml')
    List<UserStats> getGetUserStatsXMLRepresentation(@QueryParam('begin') String dtInicio, @QueryParam('end') String dtFim, @QueryParam('userEmail') String email) {
        def t1 = System.currentTimeMillis()
        if(dtInicio ==null || dtFim ==null){
            return ""
        }
        def userStats = []
        //select count(prog_title) contagem, prog_title,users.email from programmation join alert on programmation.id = alert.program_id join users on alert.user_id = users.id where users.email=\''+email+'\' and alert.hora_dispara between \''+dtInicio+'\' and \''+dtFim+'\' group by alert.user_id, prog_title,email order by contagem desc 
       def sql = Sql.newInstance( 'jdbc:postgresql://localhost:5432/ad', 'postgres',
                       'postgres', 'org.postgresql.Driver' )
        sql.eachRow('select count(prog_title) contagem, prog_title,users.email from programmation join alert on programmation.id = alert.program_id join users on alert.user_id = users.id where users.email=\''+email+'\' and alert.hora_dispara between \''+dtInicio+'\' and \''+dtFim+'\' group by alert.user_id, prog_title,email order by contagem desc ') {
           userStats.add(new UserStats(program_title:it.prog_title,user_email:it.email,frequencia:it.contagem))
        }
        def tt = System.currentTimeMillis() - t1       
        new Statistic(servico: Servicos.findByName('getUserStatsXML'), totalTime: tt, date: new Date()).save()
        userStats
    }   
}

